import { ref } from 'vue'
import { defineStore } from 'pinia'

import { getSessionStorageObj } from '../utils/common.js'

export const createUserStore = defineStore('user', () => {
  // 1.定义管理用户数据的state
  const userInfo = ref({})

  // 2.定义获取接口数据的action函数
  const setUserInfo = (newUserInfo) => {
    userInfo.value = newUserInfo
    sessionStorage.setItem('userInfo', JSON.stringify(newUserInfo))
  }

  const getUserInfo = () => {
    return getSessionStorageObj('userInfo')
  }

  // 3.定义重置用户信息的方法
  const resetUserInfo = () => {
    userInfo.value = {}
    sessionStorage.removeItem('userInfo')
  }

  // 4.以对象的格式把state和action return
  return {
    userInfo,
    setUserInfo,
    getUserInfo,
    resetUserInfo
  }
}, {
  // 用于持久化
  persist: true
})